package org.offsync.nio

import java.net.SocketAddress
import java.nio.channels.SocketChannel
import java.nio.channels.spi.SelectorProvider
import java.nio.ByteBuffer
import java.net.Socket

case class NioSocketChannel(protected override val channel: SocketChannel) extends NioSelectableChannel(channel) {
  def connect(
      remote: SocketAddress): Boolean = channel.connect(remote) 

  def finishConnect(): Boolean = channel.finishConnect() 

  def isConnected: Boolean = channel.isConnected
  
  def isConnectionPending: Boolean = channel.isConnectionPending 

  def read(
      dst: ByteBuffer): Int = channel.read(dst)

  def read(
      dsts: Array[ByteBuffer]): Long = channel.read(dsts)

  def read(
      dsts: Array[ByteBuffer],
      offset: Int,
      length: Int): Long = channel.read(dsts, offset, length)

  def socket: Socket = channel.socket

  def write(
    src: ByteBuffer): Int = channel.write(src)

  def write(
    srcs: Array[ByteBuffer]): Long = channel.write(srcs)

  def write(
    srcs: Array[ByteBuffer],
	offset: Int,
    length: Int): Long = channel.write(srcs, offset, length)
}

object NioSocketChannel {
  def open(): NioSocketChannel = {
    val channel = SocketChannel.open()
    channel.configureBlocking(false)
    return NioSocketChannel(channel)
  }
  
  def open(
    remote: SocketAddress): NioSocketChannel = NioSocketChannel(SocketChannel.open(remote))
}
